
/**
 * copyright(c) 2013 www.jiongshibaoliao.com, All Rights Reserved.
 * project: jiongshibaoliao 
 * author: 曾帅
 * date: 2014-1-10 下午09:02:54
 * version: v1.0
 */

package com.jiongshibaoliao.dao.impl;

import org.springframework.beans.factory.annotation.Value;

import com.jiongshibaoliao.dao.BaseDao;
import com.jiongshibaoliao.exception.JiongException;
import com.jiongshibaoliao.mapper.BaseMapper;
import com.jiongshibaoliao.model.BaseModel;

/**
 * @project jiongshibaoliao
 * @author 曾帅 
 * @version 1.0
 * @date 2014-1-10 下午09:02:54   
 */

public abstract class BaseDaoImpl implements BaseDao {
	
	@Value("${retry.times}")
    private int retryTimes;
	
	/**
	 * 
	 * @author 曾帅
	 * @version 1.0
	 * @date 2014-1-9 下午05:06:01
	 * @see com.jiongshibaoliao.dao.BaseDao#create(java.lang.Object)
	 */
	@Override
	public <T> void create(T entity) {
		getMapper().create(entity);
	}

	
	/**
	 * 
	 * @author 曾帅
	 * @version 1.0
	 * @throws JiongException 
	 * @date 2014-1-9 下午05:06:01
	 * @see com.jiongshibaoliao.dao.BaseDao#delete(java.lang.String)
	 */
	@Override
	public void delete(long id) throws JiongException {
		getMapper().delete(id);
	}

	
	/**
	 * 
	 * @author 曾帅
	 * @version 1.0
	 * @date 2014-1-9 下午05:06:01
	 * @see com.jiongshibaoliao.dao.BaseDao#getEntityById(java.lang.String)
	 */
	@Override
	public Object getEntityById(long id) {
		return getMapper().getEntityById(id);
	}

	
	/**
	 * @author 曾帅
	 * @version 1.0
	 * @date 2014-1-10 下午09:09:51
	 * @param <T>
	 * @param baseMapper
	 * @param entity
	 * @throws JiongException void
	 */
	public <T> void modify(T entity) throws JiongException {
		BaseModel baseEntity = (BaseModel) entity;
		int upNum = getMapper().modify(baseEntity);
		if(upNum < 1) {
			for(int i = 0; i < retryTimes; i++) {
				BaseModel _baseEntity = (BaseModel) getMapper().getEntityById(baseEntity.getId());
				baseEntity.setVersion(_baseEntity.getVersion());
				int _upNum = getMapper().modify(baseEntity);
				if(_upNum > 0) {
					return ;
				}
			}
			throw new JiongException("请求过期， 请重新操作！");
		}
	}
	
	public abstract BaseMapper getMapper();

}
